package com.ruoyi.web.controller.tool;

import java.util.Collections;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RandomStringGenerator {

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int STRING_LENGTH = 5;
    private static final int NUM_THREADS = 10; // Number of threads

    public static Set<String> generateUniqueStrings(int numStrings) {
        ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
        Set<String> uniqueStrings = Collections.newSetFromMap(new ConcurrentHashMap<>());
        int stringsPerThread = numStrings / NUM_THREADS;
        int remainingStrings = numStrings % NUM_THREADS;

        for (int i = 0; i < NUM_THREADS; i++) {
            int count = stringsPerThread + (i < remainingStrings ? 1 : 0);
            executor.submit(new StringGeneratorTask(count, uniqueStrings));
        }

        executor.shutdown();
        while (!executor.isTerminated()) {
            // Wait for all tasks to complete
        }
        return uniqueStrings;
    }

    static class StringGeneratorTask implements Callable<Void> {
        private final int numStrings;
        private final Set<String> uniqueStrings;

        public StringGeneratorTask(int numStrings, Set<String> uniqueStrings) {
            this.numStrings = numStrings;
            this.uniqueStrings = uniqueStrings;
        }

        @Override
        public Void call() {
            Random random = new Random();
            while (uniqueStrings.size() < numStrings) {
                String randomString = generateRandomString(random);
                uniqueStrings.add(randomString);
            }
            return null;
        }

        private String generateRandomString(Random random) {
            StringBuilder sb = new StringBuilder(STRING_LENGTH);
            for (int i = 0; i < STRING_LENGTH; i++) {
                sb.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
            }
            return sb.toString();
        }
    }
}
